import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import socketManager from '@/utils/socketManager'
import request from '@/utils/request'

// 传输记录接口
interface TransferRecord {
  id: number
  fileName: string
  originalName: string
  fileSize: number
  transferStatus: 'PENDING' | 'IN_PROGRESS' | 'COMPLETED' | 'FAILED' | 'CANCELLED'
  progressPercentage: number
  transferredBytes: number
  transferSpeed: number
  startTime?: string
  endTime?: string
  errorMessage?: string
  createdAt: string
}

// 传输统计接口
interface TransferStatistics {
  inProgressCount: number
  completedCount: number
  failedCount: number
  totalCount: number
}

/**
 * 全局传输状态管理Store
 */
export const useTransferStore = defineStore('transfer', () => {
  // ==================== 状态数据 ====================
  
  // Socket连接状态
  const isConnected = ref(false)
  const socketId = ref<string | null>(null)
  const isConnecting = ref(false)
  const connectionState = ref('disconnected')
  const reconnectAttempts = ref(0)
  const showConnectionWarning = ref(false)
  
  // 传输数据
  const activeTransfers = ref<TransferRecord[]>([])
  const transferHistory = ref<TransferRecord[]>([])
  const statistics = ref<TransferStatistics>({
    inProgressCount: 0,
    completedCount: 0,
    failedCount: 0,
    totalCount: 0
  })
  
  // UI状态
  const isLoading = ref(false)
  const error = ref<string | null>(null)
  
  // 分页状态
  const currentPage = ref(1)
  const pageSize = ref(20)
  const totalRecords = ref(0)
  
  // ==================== 计算属性 ====================
  
  const hasActiveTransfers = computed(() => activeTransfers.value.length > 0)
  const connectionStatus = computed(() => {
    if (isConnecting.value) return 'connecting'
    if (isConnected.value) return 'connected'
    return 'disconnected'
  })
  
  // ==================== Socket.IO 连接管理 ====================
  
  /**
   * 初始化Socket.IO连接
   */
  const initSocket = async (userId: number) => {
    if (isConnecting.value || isConnected.value) {
      // console.log('🔗 Socket已连接或正在连接中')
      return
    }

    try {
      isConnecting.value = true
      error.value = null

      // 监听连接状态变化
      socketManager.onConnectionStateChange('transfer-store', (state, attempts) => {
        connectionState.value = state
        reconnectAttempts.value = attempts

        // 更新连接状态
        isConnected.value = state === 'connected'
        isConnecting.value = state === 'connecting' || state === 'reconnecting'

        // 智能显示警告：只有在多次重连失败后才显示
        if (state === 'failed' && attempts >= 3) {
          showConnectionWarning.value = true
          ElMessage.error('实时连接失败，传输进度可能无法实时更新')
        } else if (state === 'connected') {
          showConnectionWarning.value = false
          if (attempts > 0) {
            ElMessage.success('实时连接已恢复')
          }
        }
      })

      await socketManager.connect(userId)
      socketId.value = socketManager.socketId || null

      // 设置Socket事件监听器
      setupSocketListeners()

      // 延迟加载初始数据，确保事件监听器已设置
      setTimeout(() => {
        loadInitialData()
      }, 100)

    } catch (error) {
      // 不立即显示错误，让重连机制和状态监听器处理
      console.error('Socket连接失败:', error)
    } finally {
      // isConnecting状态由连接状态监听器管理，不在这里设置
    }
  }
  
  /**
   * 断开Socket连接
   */
  const disconnectSocket = () => {
    socketManager.disconnect()
    isConnected.value = false
    socketId.value = null
    activeTransfers.value = []
  }
  
  /**
   * 重新连接Socket
   */
  const reconnectSocket = async (userId: number) => {
    disconnectSocket()
    await initSocket(userId)
  }
  
  // ==================== Socket事件监听器 ====================
  
  /**
   * 设置Socket事件监听器
   */
  const setupSocketListeners = () => {
    // 监听活跃传输列表更新事件
    socketManager.on('activeTransfers', (data) => {
      const transfers = data.transfers || []
      // console.log('📥 收到活跃传输列表:', transfers.length, '个传输', transfers) // 开发调试用

      // 更新活跃传输列表状态
      activeTransfers.value = transfers
      updateStatistics()

      // 开发环境调试：显示传输状态详情
      // if (transfers.length > 0) {
      //   transfers.forEach(transfer => {
      //     console.log(`📊 传输记录: ${transfer.originalName} - ${transfer.transferStatus} - ${transfer.progressPercentage}%`)
      //   })
      // }
    })
    
    // 监听传输进度更新事件
    socketManager.on('transferProgress', (data) => {
      console.log('📊 收到传输进度:', data) // 临时开启调试

      // 更新对应传输记录的进度信息
      updateTransferProgress(data)
    })

    // 监听传输完成
    socketManager.on('transferCompleted', (data) => {
      console.log('🏁 收到传输完成事件:', data) // 临时开启调试
      handleTransferCompleted(data)
    })
    
    // 监听传输历史
    socketManager.on('transferHistory', (data) => {
      const records = data.records || []
      const totalElements = data.totalElements || 0

      transferHistory.value = records
      totalRecords.value = totalElements
      updateStatistics()

      // 数据加载完成
      isLoading.value = false
    })
    
    // 监听历史记录清除
    socketManager.on('transferHistoryCleared', () => {
      transferHistory.value = []
      totalRecords.value = 0
      updateStatistics()
      ElMessage.success('传输历史已清空')
    })
  }
  
  // ==================== 数据操作方法 ====================
  
  /**
   * 加载初始数据
   */
  const loadInitialData = () => {
    if (!isConnected.value) {
      return
    }

    try {
      isLoading.value = true

      // 请求传输历史记录
      socketManager.emit('getTransferHistory', {
        page: currentPage.value - 1,
        size: pageSize.value
      })

    } catch (error) {
      isLoading.value = false
    }
  }
  
  /**
   * 更新传输进度
   */
  /**
   * 更新传输进度
   * @param progressData Socket.IO传来的进度数据
   */
  const updateTransferProgress = (progressData: any) => {
    // 查找对应的传输记录
    const index = activeTransfers.value.findIndex(t => t.id === progressData.recordId)
    console.log('🔄 更新传输进度:', progressData.recordId, '进度:', progressData.progress, '找到索引:', index)

    if (index !== -1) {
      // 找到对应记录，更新进度信息
      const oldTransfer = activeTransfers.value[index]
      activeTransfers.value[index] = {
        ...oldTransfer,
        progressPercentage: progressData.progress || oldTransfer.progressPercentage,
        transferredBytes: progressData.transferredBytes || oldTransfer.transferredBytes,
        transferSpeed: progressData.speed || oldTransfer.transferSpeed,
        transferStatus: progressData.status || oldTransfer.transferStatus
      }
      updateStatistics()
      console.log('✅ 传输进度已更新:', {
        id: activeTransfers.value[index].id,
        fileName: activeTransfers.value[index].originalName,
        progress: activeTransfers.value[index].progressPercentage,
        status: activeTransfers.value[index].transferStatus
      })
    } else {
      // 未找到对应记录，创建新的传输记录（处理Socket.IO事件顺序问题）
      console.log('🆕 创建新的传输记录:', progressData.recordId)
      const newTransfer = {
        id: progressData.recordId,
        originalName: progressData.fileName || '未知文件',
        fileName: progressData.fileName || '未知文件',
        fileSize: progressData.totalBytes || 0,
        progressPercentage: Math.max(progressData.progress || 0, 0), // 确保至少显示0%
        transferredBytes: progressData.transferredBytes || 0,
        transferSpeed: progressData.speed || 0,
        transferStatus: progressData.status || 'IN_PROGRESS',
        transferType: 'UPLOAD',
        createdAt: new Date().toISOString()
      }
      activeTransfers.value.push(newTransfer)
      updateStatistics()
      console.log('✅ 新传输记录已添加:', newTransfer)
    }
  }
  
  /**
   * 处理传输完成
   */
  /**
   * 处理传输完成事件
   * @param completedData Socket.IO传来的完成数据
   */
  const handleTransferCompleted = (completedData: any) => {
    console.log('🏁 transfer.ts处理传输完成:', completedData)

    // 先更新传输状态为完成，让用户看到最终状态
    const index = activeTransfers.value.findIndex(t => t.id === completedData.recordId)
    if (index !== -1) {
      activeTransfers.value[index] = {
        ...activeTransfers.value[index],
        transferStatus: 'COMPLETED', // 强制设置为完成状态
        progressPercentage: 100,
        transferredBytes: activeTransfers.value[index].fileSize, // 确保显示完整大小
        transferSpeed: 0 // 完成后速度为0
      }
      console.log('✅ 传输状态已更新为完成:', activeTransfers.value[index])

      // 立即更新统计信息
      updateStatistics()

      // 立即刷新传输历史，确保完成记录能立即显示
      loadTransferHistory()
    } else {
      console.warn('⚠️ 未找到对应的传输记录:', completedData.recordId)
    }

    // 延迟0.3秒后从活跃传输中移除，让用户有时间看到完成状态
    // 注意：这里只是从前端活跃列表移除，不删除数据库记录，记录会保留在传输历史中
    setTimeout(() => {
      const beforeCount = activeTransfers.value.length
      activeTransfers.value = activeTransfers.value.filter(t => t.id !== completedData.recordId)
      const afterCount = activeTransfers.value.length
      updateStatistics()
      console.log(`🗑️ 传输记录已从活跃列表移除（保留在历史中）: ${completedData.recordId}, 移除前:${beforeCount}, 移除后:${afterCount}`)
    }, 300) // 0.3秒延迟，更快的响应

    // 显示用户友好的完成通知
    if (completedData.status === 'COMPLETED') {
      ElMessage.success(`文件 ${completedData.fileName} 上传完成`)
    } else if (completedData.status === 'FAILED') {
      ElMessage.error(`文件 ${completedData.fileName} 上传失败`)
    }
  }
  
  /**
   * 加载传输历史
   */
  const loadTransferHistory = (page?: number, size?: number, filter?: string) => {
    if (!isConnected.value) {
      return
    }

    const requestPage = page !== undefined ? page : currentPage.value - 1
    const requestSize = size !== undefined ? size : pageSize.value
    const requestFilter = filter || 'all'

    socketManager.emit('getTransferHistory', {
      page: requestPage,
      size: requestSize,
      filter: requestFilter
    })
  }
  
  /**
   * 清空传输历史
   */
  const clearTransferHistory = () => {
    if (!isConnected.value) {
      ElMessage.warning('实时连接未建立，无法清空历史记录')
      return
    }

    socketManager.emit('clearTransferHistory', {})
  }

  /**
   * 删除传输记录
   */
  const deleteTransferRecord = async (transferId: number) => {
    try {
      // 使用request工具调用后端API删除传输记录
      await request.delete(`/transfer/records/${transferId}`)

      // 从前端状态中移除
      activeTransfers.value = activeTransfers.value.filter(t => t.id !== transferId)
      updateStatistics()

    } catch (error) {
      console.error('删除传输记录失败:', error)
      throw error
    }
  }
  
  /**
   * 更新统计信息
   */
  const updateStatistics = () => {
    statistics.value = {
      inProgressCount: activeTransfers.value.length,
      completedCount: transferHistory.value.filter(t => t.transferStatus === 'COMPLETED').length,
      failedCount: transferHistory.value.filter(t => t.transferStatus === 'FAILED').length,
      totalCount: transferHistory.value.length + activeTransfers.value.length
    }
  }
  
  /**
   * 分页处理
   */
  const handlePageChange = (page: number, filter?: string) => {
    currentPage.value = page
    loadTransferHistory(page - 1, undefined, filter)
  }

  const handleSizeChange = (size: number, filter?: string) => {
    pageSize.value = size
    currentPage.value = 1
    loadTransferHistory(0, size, filter)
  }
  
  // ==================== 返回状态和方法 ====================
  
  return {
    // 状态
    isConnected,
    socketId,
    isConnecting,
    connectionState,
    reconnectAttempts,
    showConnectionWarning,
    activeTransfers,
    transferHistory,
    statistics,
    isLoading,
    error,
    currentPage,
    pageSize,
    totalRecords,
    
    // 计算属性
    hasActiveTransfers,
    connectionStatus,
    
    // 方法
    initSocket,
    disconnectSocket,
    reconnectSocket,
    loadInitialData,
    updateStatistics,
    loadTransferHistory,
    clearTransferHistory,
    deleteTransferRecord,
    handlePageChange,
    handleSizeChange
  }
})
